#include<sys/socket.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<netinet/in.h>

void Usage()
{
    printf("Usage: ./http_test [ip] [port]\n");
}
int main(int argc,char *argv[])
{
    // if(argc!=3)
    // {
    //     Usage();
    //     return 1;
    // }
    int fd=socket(AF_INET,SOCK_STREAM,0);
    if(fd<0)
    {
        perror("sock_create_error");
        return 1;
    }
    struct sockaddr_in addr;
    addr.sin_family=AF_INET;
    addr.sin_addr.s_addr=inet_addr(INADDR_ANY);
    addr.sin_port=htons((int16_t)8888);

    int ret=bind(fd,(sockaddr*)&addr,sizeof(addr));
    if(ret<0)
    {
        perror("Bind_error");
        return 1;
    }
    ret=listen(fd,10);
    if(ret<0)
    {
        perror("listen_error");
        return 1;
    }
    while(1)
    {
        struct sockaddr_in newaddr;
        socklen_t len;
        int client_fd=accept(fd,(sockaddr*)&newaddr,&len);
        if(client_fd<0)
        {
            perror("accept_error");
            continue;
        }
        char input_buf[1024*10]={0};
        ssize_t read_size=read(client_fd,input_buf,sizeof(input_buf)-1);
        if(read_size<0)
        {
            perror("read_error");
            return 1;
        }
        printf("we recv request:%s",input_buf);
        char buf[1024]={0};
        const char* hello="<h1>hello world</h1>";
        sprintf(buf,"HTTP/1.0 200 OK\nContent-Length:%lu\n\n%s",strlen(hello),hello);
        write(client_fd,buf,strlen(buf));
    }
    return 0;
}